package com.fufan.mongodb.simple_mongodb;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/**
 * 
 * 处理simple-mongdodb数据库的操作
 * @author fufan
 *
 */
public class SimpleMongodb {
	
	public static final Logger logger = LoggerFactory.getLogger(SimpleMongodb.class);
	private static final String _uuid = "_uuid";
	
	
	/**
	 * 获取某个表的全部数据
	 * 
	 * @param path
	 * @param tablename
	 * @return
	 * @throws Exception
	 */
	public List<Map> loadTableDatas(String path, String tablename) 
			throws JDOMException, IOException {
		Gson gson = new Gson();
		FileInputStream file = new FileInputStream(path);
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(file);
		Element root = document.getRootElement();

		List<Map> l = new ArrayList();
		List<Element> list = root.getChildren();
		for (Element x : list) {
			if (x.getAttributeValue("name").equals(tablename)) {
				List<Element> al = x.getChildren();
				for (Element s : al) {
					String data = s.getText();
					if (data == null) {
						break;
					}
					Map mp = gson.fromJson(data, Map.class);
					l.add(mp);
				}
			}
		}
		return l;
	}
	
	
	/**
	 * 表插入一条数据
	 * 
	 * @param path
	 * @param tablename
	 * @param po
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public boolean add(String path, String tablename, Object po)
			throws JDOMException, IOException {
		Gson gson = new Gson();
		boolean flag = false;
		FileInputStream file = new FileInputStream(path);
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(file);
		Element root = document.getRootElement();

		List<Element> list = root.getChildren();
		for (Element x : list) {
			if (x.getAttributeValue("name").equals(tablename)) {
				Map base = new HashMap();
				base.put(_uuid, UUID.randomUUID().toString());
				Element data = new Element("data");
				String json = gson.toJson(po);
				Map mp = gson.fromJson(json, Map.class);
				base.putAll(mp);
				data.addContent(gson.toJson(base));
				x.addContent(data);
				flag = true;
			}
		}
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream(path));
		if(flag)
			logger.debug("addData success");
		else
			logger.debug("0 data has been added");
		return flag;
	}
	
	/**
	 * 删除一条数据
	 * @param path
	 * @param tableName
	 * @param po
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public boolean delete(String path, String tableName, Object po) throws JDOMException, IOException{
		FileInputStream out = new FileInputStream(path);
		Gson gson = new Gson();
		boolean flag = false;
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(out);
		Element root = doc.getRootElement();
		List<Element> tables = root.getChildren();
		
		for(Element e:tables){
			List<Element> al = e.getChildren();
			if((tableName==null?"":tableName).equals(e.getAttributeValue("name"))){
				for (Element s : al) {
					// 如果定位Data[通过UUID唯一标示]
					Map mp = gson.fromJson(s.getText(), Map.class);
					Map newmp = gson.fromJson(gson.toJson(po), Map.class);
					if (mp.get(_uuid).equals(newmp.get(_uuid))) {
						e.removeContent(s);
						flag = true;
						break;
					}
				}
			}
		}
		XMLOutputter output = new  XMLOutputter();
		
		output.output(doc, new FileOutputStream(path));
		if(flag)
			logger.debug("deleteData success");
		else
			logger.debug("0 data has been deleted");
		
		return flag;
	}
	
	/**
	 * 更新一条数据
	 * @param path
	 * @param tableName
	 * @param po
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public boolean update(String path, String tableName, Object po) throws JDOMException, IOException{
		
		FileInputStream out = new FileInputStream(path);
		Gson gson = new Gson();
		boolean flag = false;
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(out);
		Element root = doc.getRootElement();
		List<Element> tables = root.getChildren();
		
		for(Element e: tables){
			List<Element> al = e.getChildren();
			if((tableName==null?"":tableName).equals(e.getAttributeValue("name"))){
				for (Element s : al) {
					// 如果定位Data[通过UUID唯一标示]
					Map mp = gson.fromJson(s.getText(), Map.class);
					Map newmp = gson.fromJson(gson.toJson(po), Map.class);
					if (mp.get(_uuid).equals(newmp.get(_uuid))) {
						mp.putAll(newmp);
						Element newE = new Element("data");
						newE.setText(gson.toJson(mp));
						e.removeContent(s);
						e.addContent(newE);
						flag = true;
						break;
					}
				}
			}
		}
		XMLOutputter output = new  XMLOutputter();
		output.output(doc, new FileOutputStream(path));
		
		if(flag)
			logger.debug("updateData success");
		else
			logger.debug("0 data has been updated");
		
		return flag;
		
	}
	
	/**
	 * 创建数据库
	 * @param path
	 * @throws IOException 
	 */
	public void createDatabase(String path) throws IOException{
		FileOutputStream out = new FileOutputStream(path);
		
		Document doc = new Document();
		Element root = new Element("databse");
		Element table1 = new Element("table");
		table1.setAttribute(new Attribute("name", "test"));
		Element table2 = new Element("table");
		table2.setAttribute(new Attribute("name", "system-indexs"));
		Element table3 = new Element("table");
		table3.setAttribute(new Attribute("name", "system-users"));
		
		root.addContent(table1);
		root.addContent(table2);
		root.addContent(table3);
		
		doc.setRootElement(root);
		
		XMLOutputter xmlout = new XMLOutputter();
		xmlout.output(doc,out);
		
		logger.info("database created success");
		
		
	}

}
